package com.caltco.cargo.ops.modules.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.caltco.cargo.ops.auth.bo.AdminUserDetails;
import com.caltco.cargo.ops.common.base.gen.BaseServiceImpl;
import com.caltco.cargo.ops.modules.sys.dao.DailyTaskDao;
import com.caltco.cargo.ops.modules.sys.entity.DailyTask;
import com.caltco.cargo.ops.modules.sys.request.DailyTaskRequest;
import com.caltco.cargo.ops.modules.sys.request.DeleteDailyTaskRequest;
import com.caltco.cargo.ops.modules.sys.service.DailyTaskService;
import com.caltco.cargo.ops.modules.sys.vo.DailyTaskDayVO;
import com.caltco.cargo.ops.modules.sys.vo.DailyTaskVO;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.List;

@Service
public class DailyTaskServiceImp extends BaseServiceImpl<DailyTaskDao, DailyTask> implements DailyTaskService {
    private final DailyTaskDao dailyTaskDao;

    public DailyTaskServiceImp(DailyTaskDao dailyTaskDao) {
        this.dailyTaskDao = dailyTaskDao;
    }

    public Long getUserIdByToken() {
        return ((AdminUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUserEntity().getUserId();
    }

    public Date getStartOfWeek() {
        LocalDate startOfWeek = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        return Date.valueOf(startOfWeek); // 转换成 java.sql.Date
    }

    public Date getEndOfWeek() {
        LocalDate endOfWeek = LocalDate.now().with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        return Date.valueOf(endOfWeek); // 转换成 java.sql.Date
    }

    public Date getToday() {
        return Date.valueOf(LocalDate.now());  // 获取当天日期（YYYY-MM-DD）
    }

    public Date getYesterday() {
        return Date.valueOf(LocalDate.now().minusDays(1));
    }


    @Override
    public DailyTaskVO getDailyTaskByDay() {
        DailyTask dailyTask = dailyTaskDao.selectOne(new LambdaQueryWrapper<DailyTask>()
                .eq(DailyTask::getDate, getToday())
                .eq(DailyTask::getUserId, getUserIdByToken()));
        DailyTaskVO dailyTaskVO = new DailyTaskVO();
        if (dailyTask == null) return null;
        BeanUtil.copyProperties(dailyTask, dailyTaskVO);
        return dailyTaskVO;
    }

    @Override
    public Boolean setDailyTaskByDay(DailyTaskRequest request) {
        DailyTask dailyTask = new DailyTask();
        BeanUtil.copyProperties(request, dailyTask);
        Boolean tem = dailyTaskDao.exists(new LambdaQueryWrapper<DailyTask>()
                .eq(DailyTask::getUserId, getUserIdByToken())
                .eq(DailyTask::getDate, getToday()));
        if (!tem) {
            dailyTask.setUserId(getUserIdByToken());
            dailyTask.setDate(getToday());
            this.save(dailyTask);
        } else {
            this.update(dailyTask, new LambdaQueryWrapper<DailyTask>()
                    .eq(DailyTask::getUserId, getUserIdByToken())
                    .eq(DailyTask::getDate, getToday()));
        }
        return true;
    }

    @Override
    public Boolean deleteDailyTask(DeleteDailyTaskRequest request) {
        DailyTask dailyTask = dailyTaskDao.selectOne(new LambdaQueryWrapper<DailyTask>()
                .eq(DailyTask::getUserId, getUserIdByToken())
                .eq(DailyTask::getDate, getToday()));
        if (dailyTask != null){
            if (request.getType() == 0){
                dailyTask.setReviewsWordNum(0);
            }else {
                dailyTask.setLearnWordNum(0);
            }
            dailyTaskDao.updateById(dailyTask);
        }
        return true;
    }


    @Override
    public DailyTaskDayVO getDailyTaskByMonth() {
        Long userId = getUserIdByToken();
        // 获取当前月的起始和结束日期
        LocalDate now = LocalDate.now();
        Date startDate = Date.valueOf(now.withDayOfMonth(1));
        Date endDate = Date.valueOf(now.withDayOfMonth(now.lengthOfMonth()));

        // 查询总完成天数
        Integer totalDays = dailyTaskDao.countCompletedDaysInMonth(userId, startDate, endDate);

        // 查询符合条件的日期列表
        List<Date> dates = dailyTaskDao.selectQualifiedDatesInMonth(userId, startDate, endDate);

        // 计算最大连续天数
        int maxConsecutive = calculateMaxConsecutiveDays(dates);

        DailyTaskDayVO dailyTaskDayVO = new DailyTaskDayVO();

        dailyTaskDayVO.setTotalDays(totalDays);
        dailyTaskDayVO.setMaxTotalDays(maxConsecutive);
        dailyTaskDayVO.setDates(dates);
        return dailyTaskDayVO;
    }

    private int calculateMaxConsecutiveDays(List<Date> dates) {
        if (dates.isEmpty()) return 0;

        int max = 1;
        int current = 1;

        for (int i = 1; i < dates.size(); i++) {
            LocalDate prev = dates.get(i - 1).toLocalDate();
            LocalDate curr = dates.get(i).toLocalDate();

            if (prev.plusDays(1).equals(curr)) {
                current++;
                max = Math.max(max, current);
            } else {
                current = 1;
            }
        }

        return max;
    }
}
